package brc.syntacticTree;

import java.io.IOException;
import java.io.Writer;

import brc.symbolTable.LabelMaker;

public class WhileTreeNode implements TreeNode {
	/**
	 * 
	 */
	private static final long serialVersionUID = 468604483927241230L;
	private BooleanExprNode condition;
	private CodeBlockNode codeBlock;
	
	
	public WhileTreeNode(BooleanExprNode condition, CodeBlockNode codeBlock) {
		if (condition == null || codeBlock == null) {
			throw new NullPointerException("The while statement must have condition and a codeBlock");
		}
		this.condition = condition;
		this.codeBlock = codeBlock;
	}

	public BooleanExprNode getCondition() {
		return this.condition;
	}
	public CodeBlockNode getCodeBlock() {
		return this.codeBlock;
	}
	
	@Override
	public void writeAssembly(Writer writer) throws IOException {
		String whileLabel = LabelMaker.next("while");
		String endWhileLabel = LabelMaker.next("endWhile");
		
		writer.write(whileLabel + ":\r\n");
		this.condition.writeAssembly(writer);
		writer.write("ifeq " + endWhileLabel + "\r\n");
		this.codeBlock.writeAssembly(writer);
		writer.write("goto " + whileLabel + "\r\n");
		writer.write(endWhileLabel + ":\r\n");
	}

	@Override
	public void semanticCheck() throws SemanticException {
		this.condition.semanticCheck();
		this.codeBlock.semanticCheck();
	}
}
